<template>
  <div id="map-container">
    <div v-if="home_state!=='style_loading'" :class="[home_state ==='history_single'||home_state ==='realtime_single'||home_state ==='company_group'||home_state ==='history_hotMap'||home_state === 'alarm_info'||cur_nav=='2'||cur_nav=='3'||cur_nav=='4'?'leftPanel':'','map-mask']">
      <span class="focus-icon" @click="focusCenter()"></span>
      <span class="traffic-icon" :class="{active: traffic}" @click="trafficControl()">
      </span>
      <span class="sub-icon" @click="updateMapRoom('out')"></span>
      <span class="add-icon" @click="updateMapRoom('in')"></span>
      <span class="compass-icon" @click="resetCompass()">
        <span class="reset-icon-image"></span>
      </span>
    </div>
  </div>
</template>

<script>
  import {mapGetters, mapMutations} from 'vuex'
  import eventBus from '../util/event-bus'
  import MYCONF from '../myconf'
  import MapInit from '../service/map/mapInit'
  import HomeLayerHandler from '../service/map/homeLayerHandler'
  import CityMapLayerHandler from '../service/map/cityMapLayerHandler'
  import OdLayerHandler from '../service/map/odLayerHandler'
  import TrafficLayerHandler from '../service/map/trafficLayerHandler'
  import mapHandler from '../service/map/mapHandler'
  import {initFrame, clearFrame} from '../service/map/mapFrame'
  import DateTimeHelper from '../util/datetime-helper'
  import mapHelper from '../util/map-helper'
  import env from '../util/env'
  export default {
    name: 'mapContainer',
    data () {
      return {
        historyMarkers: [],  //单车历史预警
        historyPopups: [],
        historyData: [],      //历史轨迹数据
        pathList: [],         //历史轨迹集合
        historyTimer: null,
        realTimer: null,
        playStatus: "pause",
        hisData: [],      //已通过历史轨迹
        realData: [],      //已通过历史轨迹
        realSingleData:[],  //当前单车实时阶段数据
        cityMapData:[],    //城市一张图信息
        cityMapPointList:[],//城市一张图点集合
        warnCarIds:[],    //报警车辆idList
        sTime:null,     //单车实时开始时间
        eTime:null,      //单车实时结束时间
        startTime:null,     //单车实时开始时间
        endTime:null,      //单车实时结束时间
        fCoordinate: null,
        eCoordinate: null,
        secondTime:null,
        singleAngle: 0,
        singleSpeed:0,
        traffic:false,
        curZoom:MYCONF.map.zoom,
        globalTimer:null,
        changing: false,
        mapCenter: [],
      }
    },
    mounted(){
      this.mapInit();
      this.homeLayerHandler = new HomeLayerHandler(this);
      this.cityMapLayerHandler = new CityMapLayerHandler(this);    //城市一张图地图相关
      this.odLayerHandler = new OdLayerHandler(this);        //运营数据分析地图相关
      this.trafficLayerHandler = new TrafficLayerHandler(this);     //城市交通画像地图相关
      this.mapHandler = new mapHandler(this);
      this.resetMapPos();
      this.$nextTick(() => {
        let map = this.map;
        let _this = this;
        let t = setInterval(function() {
          if (map) {
            if (map.isStyleLoaded()) {
              clearInterval(t);
              //TODO:YI
              _this.setRealTimeLayer();
             // _this.getAllCityMapData();
              _this.setGlobalInterval();
            }
          } else {
            clearInterval(t);
          }
        }, 1000);
      });
      eventBus.$on("drawHistoryPath", (pointList, result) => {
        this.hisData = [];
        this.axis_num.hour = 0;
        this.axis_num.index = 0;
        this.homeLayerHandler.drawHistoryPath(pointList);
        this.homeLayerHandler.addHistoryPath([pointList[0], pointList[1]]);
        this.homeLayerHandler.addSymbolLayer('start', pointList[0]);
        this.homeLayerHandler.addSymbolLayer('end', pointList[pointList.length - 1]);
        this.pathList = pointList;
        this.historyData = result;
      });
      eventBus.$on("filterPoint",(pointList,itemPoint)=>{
        this.cityMapLayerHandler.getRange(pointList,itemPoint);
      })
      eventBus.$on("addWarnPopup", (center, warn) => {
        this.homeLayerHandler.addWarnInfo(center, warn);
      });
      eventBus.$on('changePlayState', (state) => {
        this.updateMapDraged(false);
        this.changePlayState(state.action);
      });
      eventBus.$on("DragStop", (hour, val) => {
        this.hisData = [];
        this.drawDragPath(hour, val);
      });
      eventBus.$on("historyFinish",() => {
        this.homeLayerHandler.setAxisTimer();
      });
      eventBus.$on("exitRealTrack",() => {
        this.map.flyTo({
          center:this.single_map_state.center,
          zoom:this.single_map_state.zoom,
          speed:2
        })
      });
      eventBus.$on("exitHistorySingle",()=>{
        this.map.flyTo({
          center:this.single_map_state.center,
          zoom:this.single_map_state.zoom,
          speed:2
        })
      });
      eventBus.$on("getRealSingleData",() => {
        this.homeLayerHandler.getRealSingleData();
      });

      eventBus.$on("updateWarnCar",(list) => {
        this.warnCarIds = list;
        this.homeLayerHandler.addRealWarnCircleLayer();
        this.homeLayerHandler.addRealWarnIconLayer();

        // 激活动画
        initFrame(this.map);
      });

      eventBus.$on("clearMap",() => {
        this.clearMapAll();     //删除所有地图标记与图层
      });

      eventBus.$on("locateToCityMap",(data) => {  //城市一张图定位
        this.cityMapLayerHandler.locateToCityMap(data);
      });

      eventBus.$on("singleHistoryNoData",() => {
        setTimeout(() => {
          this.updateLoadingState(false);
        }, 500);
      });
      eventBus.$on("clearData",() => {
        this.pathList = [];
        this.historyData = [];
      });


      // for od
      eventBus.$on('drawOd', (lineData, pointData, max, min, center, zoom) => {
        this.odLayerHandler.addOdLayer(lineData, pointData, max, min, center, zoom);
      });
      eventBus.$on('distoryOd', () => {
        this.odLayerHandler.distoryOdLayer();
      });

      eventBus.$on("addOdBusLinesLayer",(odBusLines) => {
        this.odLayerHandler.addOdBusLinesLayer(odBusLines, ["coordinates"]);
      });
      eventBus.$on("addOdBusStopsLayer",(odBusStops) => {
        this.odLayerHandler.addOdBusStopsLayer(odBusStops, [ "name", "num", "rank", "coordinates"]);
        this.map.flyTo({
          center: [102.629276, 37.934373],
          zoom: 14
        })
      });
      eventBus.$on("destroyOdBusLayer",() => {
        this.odLayerHandler.destroyOdBusLayer();
      });

      // for heatmap
      eventBus.$on("heatMapTimeChange",(index) => {
        this.homeLayerHandler.changeHeatmapLayer(index);
      });

      eventBus.$on("changeMapCenterAndZoom",(center, zoom) => {
        this.homeLayerHandler.changeMapCenterAndZoom(center, zoom);
      });

      // for traffic
      eventBus.$on("trafficShow",() => {
        this.setTraffic(true)
      });
      eventBus.$on("trafficHide",() => {
        this.setTraffic(false)
      });

      // for style change
      eventBus.$on("mapStyleChange",(i) => {
        this.changeStyle(i)
      });
    },
    computed: {
      ...mapGetters(['style', 'home_state', 'cur_nav', 'single_car', 'axis_num', 'speed','isMapDraged','hotMap_time','in_type','isPopShow','isMainPopShow','alarmInfo','single_map_state','car_type','company_info', 'homeChart/selectedTime', 'pre_home_state']),
    },
    methods: {
      ...mapMutations(['updateStyle', 'updateLoadingState', 'updateMapDraged', 'updateAxisNum', 'updateHomeState', 'updateSingleCar', 'updateAlarmInfo', 'updateSingleMapState', 'updatePreHomeState','updateCarType','updateIsPopShow','updateIsTwoPop','updateIsMainPopShow']),
      mapInit: MapInit,
      resetMapPos(){
        let canvas = document.getElementsByClassName('minemap-canvas')[0];
        canvas.style.top = "0px";
        canvas.style.left = "0px";
      },
      trafficControl() {
        this.setTraffic(!this.traffic);
      },
      setTraffic(bool) {
        for (let i = 0; i < MYCONF.TRAFFIC_LAYER_IDS[this.style].length; i++) {
          const id = MYCONF.TRAFFIC_LAYER_IDS[this.style][i];
          if (bool) {
            if (this.map.getLayer(id)) this.map.setLayoutProperty(id, 'visibility', 'visible');
          } else {
            if (this.map.getLayer(id)) this.map.setLayoutProperty(id, 'visibility', 'none');
          }
        }
        this.traffic = bool;
      },
      updateMapRoom(type){
        let curZoom = this.map.getZoom();
        if (type === 'in') {
          if (curZoom < 17) {
            this.map.zoomIn()
          }
        } else {
          if (curZoom > 3) {
            this.map.zoomOut()
          }
        }
      },
      resetCompass(){
        this.map.easeTo({
          bearing: 0,
          pitch: 0
        })
      },
      setRealTimeLayer() {
        this.endTime = DateTimeHelper.getCurTime();
        this.startTime = DateTimeHelper.getMinuteTime(MYCONF.TIME_INTERVAL);
        this.homeLayerHandler.addRealPointLayer();
        this.homeLayerHandler.addRealIconLayer();
      },
      setRealSingleLayer(){
        this.realData = [];
        this.homeLayerHandler.getRealSingleData();
        eventBus.$emit('updateSingleWarnList');
      },
      changePlayState(state){
        this.homeLayerHandler.addSingleCar(this.pathList[0]);
        if (state === 'PAUSE') {
          this.homeLayerHandler.setAxisTimer();
          this.playStatus = "play";
        } else {
          this.playStatus = "pause";
          eventBus.$emit("updateHistoryAxis");
          clearInterval(this.historyTimer);
          this.historyTimer = null;
        }
      },
      drawDragPath(hour, val){
        let tempData = [];
        for (let i = 0; i < hour; i++) {
          this.historyData[i].data.map((item) => {
            tempData.push(item.point.slice(0, 2));
          });
        }
        if (val > 0) {
          for (let i = 0; i < val; i++) {
            tempData.push(this.historyData[hour].data[i].point.slice(0, 2));
          }
        }
        this.hisData = tempData;
        if (this.playStatus === "play") {
          clearInterval(this.historyTimer);
          this.historyTimer = null;
          this.homeLayerHandler.setAxisTimer();
        }
      },

      getAllCityMapData(){
        let url = MYCONF.service.infrastAll;
        this.$http.get(url)
          .then(response => {
            response = response.body;
            this.cityMapData  = response.companyInfoList;

          }, response => {
            // error callback
          });
      },

      setLayerUpdate(){
        if (!this.changing) {
          if(this.home_state === 'realtime'){
            this.homeLayerHandler.addRealPointLayer();
            this.homeLayerHandler.addRealIconLayer();
            this.homeLayerHandler.addRealWarnCircleLayer();
            this.homeLayerHandler.addRealWarnIconLayer();
            eventBus.$emit('updateGlobalWarnList',0);
          }else if(this.home_state === 'company_group'){
            this.homeLayerHandler.addRealGroupLayer();
            this.homeLayerHandler.addRealWarnCircleLayer();
            this.homeLayerHandler.addRealWarnIconLayer();
          }
        }
      },

      clearMapAll(){
        this.warnCarIds = [];//实时报警id list
        clearFrame();
        this.mapHandler.removeAllLayers();
        this.homeLayerHandler.clearHomeMap();
        clearInterval(this.realTimer);
        clearInterval(this.historyTimer);
        this.mapHandler.removeCarPopups();
        //console.log('clear')
      },

      //强制刷新
      setGlobalInterval(){
        this.globalTimer = setInterval(() => {
          this.endTime = DateTimeHelper.getCurTime();
          this.startTime = DateTimeHelper.getMinuteTime(MYCONF.TIME_INTERVAL);
          this.setLayerUpdate();
        },MYCONF.GLOBAL_INTERVAL)
      },

      changeStyle(i) {
        const map = this.map;
        if ((!this.changing) && (this.style !== i)) {
          // start loading
          this.changing = true;
          const stateNow = this.home_state;
          this.updateHomeState('style_loading');
          this.updateLoadingState(true);

          // change style
          minemap.accessToken = MYCONF.maps.token[i];
          minemap.solution = MYCONF.maps.solu[i];
          map.setStyle(MYCONF.maps.style[i]);

          // show new map
          const interval = setInterval(() => {
            if (map.isStyleLoaded()) {
              this.updateHomeState(stateNow);
              this.updateLoadingState(false);
              clearInterval(interval);
              this.changing = false;
              this.updateStyle(i);

              // disable traffic layer
              this.setTraffic(false);

              // add image
              this.mapHandler.loadImages(this.setLayerUpdate.bind(this))
            }
          }, 1000);
        }
      },

      focusCenter() {
        this.map.flyTo({
          center:MYCONF.map.center,
          speed:1.8
        });
      }
    },
    watch: {
      speed(newVal, oldVal){     //单车历史-速度触发变化
        clearInterval(this.historyTimer);
        if (this.playStatus === "play") {
          this.homeLayerHandler.setAxisTimer();
        }
      },
      home_state(newVal, oldVal){          //监控台状态切换
        if(newVal){
          this.fCoordinate = null;
          this.eCoordinate = null;
          this.secondTime = null;
          this.singleAngle = 0;
        }
        if(newVal !== 'realtime' && newVal !== 'company_group'){
          this.warnCarIds = [];//实时报警id list
          clearInterval(this.globalTimer);
        }else{
          this.setGlobalInterval();
        }
        if(newVal !== 'realtime' && newVal !== 'history_hotMap'){
          this.updateCarType(MYCONF.CAR_TYPE);
        }
        switch (newVal) {
          case 'realtime':
            this.clearMapAll();
            this.setRealTimeLayer();
            this.updateAlarmInfo({});
            eventBus.$emit("updateGlobalWarnList",0)
            if(oldVal === 'alarm_info'){ //退出报警
              this.map.stop();
              this.map.flyTo({
                center:MYCONF.map.center,
                zoom:MYCONF.map.zoom,
                speed:1.8
              });
            }
            break;
          case 'history_hotMap':
            this.clearMapAll();
            this.homeLayerHandler.addHotMapLayer(this['homeChart/selectedTime'], this['car_type']);
            this.updateAlarmInfo({});
            break;
          case 'history_single':
            this.clearMapAll();
            if(oldVal === 'realtime_single') {   //当上个页面是单车实时
              this.updateSingleMapState({   //退出历史轨迹时状态还原
                center:this.map.getCenter(),
                zoom:this.map.getZoom(),
              });
            }
            this.homeLayerHandler.addHisSingleLayer();
            this.mapHandler.setSpeedMarker();
            this.updateAlarmInfo({});
            break;
          case 'realtime_single':
            this.clearMapAll();
            if(oldVal !== 'history_single'){  //上一个页面不是历史轨迹时
              this.updateSingleMapState({   //退出实时状态还原
                center:this.map.getCenter(),
                zoom:this.map.getZoom(),
                homeState:oldVal,
                companyId:0
              });
            }
            this.setRealSingleLayer();
            this.mapHandler.setSpeedMarker();
            //this.updateAlarmInfo({});
            break;
          case 'company_group':
            this.clearMapAll();
            this.homeLayerHandler.addRealGroupLayer();
            this.updateAlarmInfo({});
            break;
          case 'alarm_info':
            this.clearMapAll();
            if(oldVal === 'realtime_single'){
              this.homeLayerHandler.addAlarmLayer();
            }
            // this.homeLayerHandler.addRealGroupLayer();
            break;
          default:
            // this.clearMapAll();
            break;
        }
        this.updatePreHomeState(oldVal);
      },
      realSingleData(newVal, oldVal) {
        // if (newVal !== oldVal && newVal.length > 0 && this.home_state === 'realtime_single') {
        if (this.home_state === 'realtime_single') {

          clearInterval(this.realTimer);
          this.homeLayerHandler.addRealSingleLayer();
        }else{
          clearInterval(this.realTimer);
        }
      },
      cur_nav(newVal, oldVal){     //主菜单变化
        switch (newVal) {
          case '1':
            clearInterval(this.globalTimer);
            this.setGlobalInterval();
            this.updateHomeState('realtime');
            map.setCenter(MYCONF.map.center);
            map.setZoom(MYCONF.map.zoom);
            map.setPitch(0);
            break;
          case '2':
            this.updateHomeState('');
            this.clearMapAll();
            this.getAllCityMapData();
            map.setCenter(MYCONF.map.center);
            map.setZoom(MYCONF.map.zoom);
            map.setPitch(60);

            break;
          case '3':
            this.updateHomeState('');
            this.clearMapAll();
            map.setCenter(MYCONF.map.center);
            map.setZoom(MYCONF.map.zoom);
            map.setPitch(0);
            break;
          case '4':
            this.updateHomeState('');
            this.clearMapAll();
            map.setCenter(MYCONF.map.center);
            map.setZoom(MYCONF.map.zoom);
            map.setPitch(0);
            break;
          default:
            break;
        }
      },
      hotMap_time(newVal, oldVal){
        if(newVal !== oldVal){
          this.clearMapAll();
          console.log("这里热力图时间改变")
          this.homeLayerHandler.addHotMapLayer(this['homeChart/selectedTime'], this['car_type']);
        }
      },
      cityMapData(newVal, oldVal){
        if(newVal && newVal !== oldVal){
          this.clearMapAll();
          this.cityMapLayerHandler.addCityMapLayer();
        }
      },
      in_type(newVal, oldVal){
        if(newVal && newVal !== oldVal){
          this.cityMapLayerHandler.filterCityMapLayer();
          this.mapHandler.removeCarPopups();
        }
      },
      alarmInfo(newVal, oldVal){
        if(newVal && newVal !== oldVal && newVal.id){
          this.clearMapAll();
          this.homeLayerHandler.addAlarmLayer();
          this.updateSingleCar({id:newVal.id});
          eventBus.$emit("updateAlarmCar");
        }
      },
      car_type(newVal, oldVal){
        if(newVal && newVal !== oldVal){
          this.homeLayerHandler.filterHomePointLayer();
          this.mapHandler.removeCarPopups();
        }
      },
      curZoom(newVal, oldVal){
        if(newVal && newVal !== oldVal){
          this.setLayerUpdate();
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  @import "../../static/common/common.scss";

  #map-container {
    width: 100%;
    min-height: $min-height;
    .map-mask {
      position: absolute;
      z-index: 100;
      bottom: 10px;
      left: 480px;
      transition: left ease 0.1s;
      &.leftPanel {
        left: 20px;
        transition: left ease 0.5s;
      }
      span {
        width: 42px;
        height: 43px;
        display: block;
        margin-top: 2px;
        cursor: pointer;
        background-color: #fff;
        background-position: center;
        background-repeat: no-repeat;

        &.focus-icon {
          background-image: url("../../static/images/index/focus-icon.png");
        }

        &.traffic-icon {
          background-image: url("../../static/images/index/traffic.png");

          &.active {
            background-image: url("../../static/images/index/traffic-active.png");
          }
        }

        &.add-icon {
          background-image: url("../../static/images/index/in-icon.png");
        }
        &.sub-icon {
          background-image: url("../../static/images/index/out-icon.png");
        }
        &.compass-icon {
          background-image: url("../../static/images/index/base.png");
          overflow: hidden;

          .reset-icon-image {
            margin-top: 0px;
            display: block;
            width: 100%;
            height: 100%;
            background: url("../../static/images/index/reset.png") no-repeat center;
          }
        }
        &:hover {
          background-color: #eee;
          transform: scale(1.03);
        }
      }
    }
  }
</style>
